﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
using SLSYJ.Controllers.DTOs;
using SLSYJ.Core;
using SLSYJ.Data;
using ProjectBase.Core.PersistenceSupport;
using ProjectBase.Core;
using ProjectBase.Web;
using AutoMapper;
using System.IO;
using System.Web;
using System.Web.Helpers;
using SLSYJ.Controllers.Models;



namespace SLSYJ.Controllers
{
    public class EmployeesController : Controller
    {
        public EmployeesController()
            : this(new EmployeeDao(), new SectorDao(), new CategoryDao())
        {
            
        }

        public EmployeesController(IDao<Employee> employeeDao, IDao<Sector> sectorDao, IDao<Category> categoryDao)
        {
            Check.Require(employeeDao != null, "employeeDao may not be null");
            Check.Require(sectorDao != null, "sectorDao may not be null");

            this.sectorDao = sectorDao;
            this.employeeDao = employeeDao;
            this.categoryDao = categoryDao;

            Mapper.CreateMap<SectorDTO,Sector>();
            Mapper.CreateMap<Sector, SectorDTO>();
            Mapper.CreateMap<CategoryDTO, Category>();
            Mapper.CreateMap<Category, CategoryDTO>();
            Mapper.CreateMap<BankDTO, Bank>();
            Mapper.CreateMap<Bank, BankDTO>();
            Mapper.CreateMap<EmployeeDTO, Employee>();
            Mapper.CreateMap<Employee, EmployeeDTO>();
            Mapper.CreateMap<EmployeeCategory, EmployeeCategoryDTO>();
            Mapper.CreateMap<EmployeeCategoryDTO, EmployeeCategory>();
        }

        public ActionResult List()
        {
            return View("List");
        }

        public ActionResult GetEmployeeList(string sidx, string sord, int page, int rows)
        {
            List<EmployeeDTO> employees = Mapper.Map<List<Employee>, List<EmployeeDTO>>(employeeDao.LoadAll());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = employees.Count;
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            List<object> list = GetRowsFromList(employees);

            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = list
            };
            return Json(jsonData,JsonRequestBehavior.AllowGet);
        }

        [HttpPost] 
        public PartialViewResult ManageSelectedGridItem(string rowid, string action)
        {
            var id =Convert.ToInt32(rowid);
            PartialViewResult retval = PartialView();
            Check.Require(id > 0, "Employee ID must be > 0");
            EmployeeDTO employee = Mapper.Map<Employee, EmployeeDTO>(employeeDao.Load(id));
            switch (action)
            {
                case "Edit":
                    retval = PartialView("_EditPartial", employee);
                    break;
                case "Details":
                    retval = PartialView("_DetailPartial", employee);
                    break;
                default:
                    break;
            }
            return retval;
        }

        [HttpPost]
        [Transaction]
        public ActionResult Create(EmployeeViewModel model)
        {
            Employee employee = Mapper.Map<EmployeeDTO, Employee>(model.DTO);
            model.DTO.ID = employeeDao.Save(employee).ID;

            return View("Detail", model.DTO);
        }

        public ActionResult Create()
        {
            EmployeeViewModel model = new EmployeeViewModel();

            model.DTO = new EmployeeDTO();
            model.Sectores = Mapper.Map<List<Sector>, List<SectorDTO>>(sectorDao.LoadAll());
            model.Categories = Mapper.Map<List<Category>, List<CategoryDTO>>(categoryDao.LoadAll());

            return View(model);
        }

        public ActionResult Details(int id)
        {
            Check.Require(id > 0, "Employee ID must be > 0");

            EmployeeDTO employee = Mapper.Map<Employee, EmployeeDTO>(employeeDao.Load(id));
            return View("Detail", employee);
        }

        public ActionResult Detail(EmployeeDTO employee)
        {
            Check.Require(employee != null, "Employee may not be null");

            return View("Detail", employee);
        }

        public ActionResult Editer(int id)
        {
            Check.Require(id > 0, "Employee ID must be > 0");

            EmployeeDTO employee = Mapper.Map<Employee, EmployeeDTO>(employeeDao.Load(id));
            return View("Edit", employee);
        }

        [HttpPost]
        [Transaction]
        public ActionResult Edit(EmployeeDTO employee)
        {
            Check.Require(employee != null, "Employee may not be null");
            Check.Require(employee.ID > 0, "Employee ID must be > 0");

            employee = Mapper.Map<Employee, EmployeeDTO>(employeeDao.SaveOrUpdate(Mapper.Map<EmployeeDTO, Employee>(employee)));
            return View("Detail", employee);
        }

        [HttpPost]
        public ActionResult Upload(List<CategoryDTO> categoryList, List<SectorDTO> sectorList)
        {
            EmployeeViewModel model = new EmployeeViewModel();
            model.DTO = new EmployeeDTO();
            model.Categories = categoryList;
            model.Sectores = sectorList;
            var image = WebImage.GetImageFromRequest();

            //model.DTO.Picture = this.UploadImage(image);

            return View("Create", model);
        }
 
        public JsonResult UploadEmployeeImage(string qqfile)
        {
            var message = string.Empty;
            HttpPostedFileBase uploadedfile = null;
            if (Request.Files.Count == 0)
                message = "No se recibieron archivos.";
            else
            {
                uploadedfile = Request.Files[0];
                message = "Imagen cargada con exito.";
            }

            //var ret = this.UploadImage(uploadedfile);
            var filename = this.UploadImage(uploadedfile);
            return new JsonResult
            {
                Data = new
                {
                    success = true,
                    fileName = filename
                },
                ContentEncoding = System.Text.Encoding.UTF8,
                ContentType = "text/html",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        [HttpPost]
        public ActionResult UploadEditer(EmployeeDTO model)
        {
            var image = WebImage.GetImageFromRequest();

            //model.Picture = this.UploadImage(image);

            return View("Edit", model);
        }

        private string UploadImage(HttpPostedFileBase httpImage)
        {
            WebImage image = new WebImage(httpImage.InputStream);
            string retval = string.Empty;
            if (image != null)
            {
                if (image.Width > 500)
                {
                    image.Resize(500, ((500 * image.Height) / image.Width));
                }

                var filename = Path.GetFileName(httpImage.FileName);
                image.Save(Path.Combine("~/uploads", filename));
                filename = Path.Combine("~/uploads", filename);
                retval = Url.Content(filename);
            }
            return retval;
        }

        private static List<object> GetRowsFromList(List<EmployeeDTO> employees)
        {
            List<object> retval = new List<object>();
            foreach (var employee in employees)
            {
                retval.Add(new
                {
                    id = employee.ID,
                    cell = new string[] { 
                        employee.Name, 
                        employee.Surname, 
                        employee.FileNumber, 
                        employee.DNInumber,
                        employee.CUILnumber
                    }
                });
            }
            return retval;
        }

        private readonly IDao<Employee> employeeDao;
        private readonly IDao<Sector> sectorDao;
        private readonly IDao<Category> categoryDao;
    }

    public static class HttpPostedFileBaseExtensions
    {
        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0);
        }
    }
}
